<template>
  <div>
    <h3>{{$route.meta.title}}</h3>
    <div class="container">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row style="margin-bottom: 20px;" type="flex" :gutter="20" justify="space-between">
            <el-col :span="5">
              <el-date-picker size="small" v-model="searchForm.reportDate" type="date" align="left" unlink-panels
                range-separator="至" placeholder="报表时间">
              </el-date-picker>
            </el-col>
            <el-col :span="5">
              <el-select  v-model="searchForm.sportId" size="small" collapse-tags @change="sportChange"
                filterable clearable placeholder="运动项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select  v-model="searchForm.sportItemId" size="small" collapse-tags @change="sportItemChange"
                filterable clearable placeholder="运动小项">
                <el-option :label="item" :value="key" v-for="(item,key,index) in sportItemData" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select  v-model="searchForm.important" size="small" collapse-tags
                filterable clearable placeholder="重点运动员">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_important" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select  v-model="searchForm.coachId" size="small" collapse-tags @change="coachChange"
                filterable clearable placeholder="教练">
                <el-option :label="item" :value="key" v-for="(item,key,index) in coachData" :key="index">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row type="flex" :gutter="20" justify="space-between">
            <el-col :span="5">
              <el-select  v-model="searchForm.playerId" size="small" collapse-tags
                filterable clearable placeholder="运动员">
                <el-option :label="item" :value="key" v-for="(item,key,index) in playerData" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select  v-model="searchForm.reportClassId" size="small" collapse-tags
                filterable clearable placeholder="报表类型">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_reportClass" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select v-show="usageId==3||usageId==4" v-model="searchForm.scenarioId" size="small" collapse-tags
                filterable clearable placeholder="场景">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_scenario" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="getSelectPlayers" style="margin: 0 10px;">搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row resizable
        :loading="loading" :data="dataList" @sort-change="sortChange" :export-config="{}">
        <vxe-table-column field="reportDate" title="报表时间" sortable></vxe-table-column>
        <vxe-table-column field="reportName" title="报表名称" sortable></vxe-table-column>
        <vxe-table-column field="reportClassName" title="报表类型" sortable></vxe-table-column>
        <vxe-table-column field="sportName" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="sportItemName" title="运动小项" sortable></vxe-table-column>
        <vxe-table-column field="coachName" title="教练员" sortable></vxe-table-column>
        <vxe-table-column field="playerName" title="运动员" sortable></vxe-table-column>
        <vxe-table-column field="important" title="重点运动员" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="110">
          <template #default="{ row }">
            <el-button @click="deleteReportData(row)" type="primary" circle size="medium" icon="el-icon-delete"></el-button>
            <el-button @click="printReportData(row)" type="primary" circle size="medium" icon="el-icon-printer"></el-button>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="printModal" title="打印预览" height="600" show-zoom resize width="800" show-footer>
      <template #default>
        <div id="myPrint">
          <totalPrintOne v-if="printData.view == 'daily'||printData.view =='some'" :printData="printData.reportJson" :memo="printData.memo" :analysisReport="true" :usageId="usageId"/>
          <assessmentAnalysis v-else-if="printData.view == 'tendency'" :printData="printData.reportJson" :analysisReport="true" :memo="printData.memo" :usageId="usageId" />
          <assessmentTotal v-else :printData="printData.reportJson" :memo="printData.memo" :analysisReport="true" :usageId="usageId" pagesize="10" />
        </div>
      </template>
      <template #footer>
        <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {pcm4coach,currentRolePlayer,pcm4sport,get_player,meta_sport_item_cache,coach_by_sport} from '@/api/dict.js'
  import {reportPlayerMap_default,getReportClass,meta_scenario,reportPlayerMap_select,deleteReportData,showReport} from '@/api/meta.js'
  import totalPrintOne from '@/components/print/totalPrintOne.vue'
  import assessmentAnalysis from '@/components/print/assessmentAnalysis.vue'
  import assessmentTotal from '@/components/print/assessmentTotal.vue'
  export default {
    components:{
      totalPrintOne,
      assessmentAnalysis,
      assessmentTotal,
    },
    data() {
      return {
        usageId: this.$route.meta.usageId,
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_coach: {},
        dict_player: {},
        dict_sport: {},
        dict_sportItem: {},
        dict_template: {},
        dict_reportClass: {},
        dict_scenario: {},
        sportItemData: {},
        coachData: {},
        playerData: {},
        dict_important: this.$store.state.user.dict_important,
        searchForm: {
          reportDate: '',
          sportId: '',
          sportItemId: '',
          importantId: '',
          coachId: '',
          playerId: '',
          reportClassId: '',
          scenarioId: '',
        },
        printData: {},
        printModal: false,
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.reportPlayerMap_default()
      })
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      printEvent() {
        const divEl = document.getElementById('myPrint')
        this.$XPrint({
          sheetName: '',
          content: divEl.innerHTML
        })
      },
      printReportData(row) {
        showReport({reportDataId:row.reportDataId}).then(res=>{
          if(res.code === 200) {
            let printData = {
              memo: JSON.parse(res.data.memo),
              reportJson: JSON.parse(res.data.reportJson),
              view: res.data.view
            }
            this.printData = printData
            this.printModal = true
          }
        })
      },
      deleteReportData(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteReportData({reportDataId:row.reportDataId}).then(res=>{
            if(res.code === 200) {
              this.$message.success('删除成功！')
              this.reportPlayerMap_default()
            }else{
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      getSelectPlayers() {
        let data = {}
        if(this.searchForm.coachId) data.coachId = this.searchForm.coachId
        if(this.searchForm.playerId) data.playerId = this.searchForm.playerId
        if(this.searchForm.reportDate) data.reportDate = this.$moment(this.searchForm.reportDate).format('YYYY-MM-DD')
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if(this.searchForm.importantId) data.isImport = this.searchForm.isImport
        if(this.searchForm.reportClassId) data.reportClassId = this.searchForm.reportClassId
        if(this.searchForm.scenarioId) data.scenarioId = this.searchForm.scenarioId
        data.usageId = this.usageId
        reportPlayerMap_select(data).then(res=>{
          if(res.code === 200) {
            this.init_data(res.data)
          }else{
            this.$message.error(res.message)
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          reportDate: '',
          sportId: '',
          sportItemId: '',
          importantId: '',
          coachId: '',
          playerId: '',
          reportClassId: '',
          scenarioId: '',
        }
        this.sportItemData = this.dict_sportItem
        this.coachData = this.dict_coach
        this.playerData = this.dict_player
        this.getSelectPlayers()
      },
      sportChange (val) {
        this.searchForm.sportItemId = ''
        this.searchForm.coachId = ''
        this.searchForm.playerId = ''
        this.sportItemData = {}
        this.coachData = {}
        this.playerData = {}
        let sportId = this.searchForm.sportId || val
        if(sportId){
          meta_sport_item_cache({sportId:sportId}).then(res=>{
            this.sportItemData = res
          })
          coach_by_sport({sportId:sportId}).then(res=>{
            this.coachData = res
          })
          get_player({usageId:this.usageId,sportId:sportId}).then(res=>{
            this.playerData = res
          })
        }
      },
      sportItemChange (val) {
        this.searchForm.coachId = ''
        this.searchForm.playerId = ''
        this.coachData = {}
        this.playerData = {}
        let sportItemId = this.searchForm.sportItemId || val
        let data = {}
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if(sportItemId){
          coach_by_sport(data).then(res=>{
            this.coachData = res
          })
          data.usageId = this.usageId
          get_player(data).then(res=>{
            this.playerData = res
          })
        }
      },
      coachChange (val) {
        this.searchForm.playerId = ''
        this.playerData = {}
        let coachId = this.searchForm.coachId || val
        let data = {}
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if(this.searchForm.coachId) data.coachId = this.searchForm.coachId
        data.usageId = this.usageId
        if(coachId){
          get_player(data).then(res=>{
            this.playerData = res
          })
        }
      },
      reportPlayerMap_default() {
        this.loading = true
        reportPlayerMap_default({usageId:this.usageId}).then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.init_data(res.data)
          }else{
            this.$message.error(res.message)
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        if(data.length!=0){
          data.forEach(item=>{
            item.important = this.dict_important[item.isImp]
          })
          this.searchProps = Object.keys(data[0])
          this.defaultDataList = data
        }else{
          this.defaultDataList = []
        }
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          pcm4coach().then(res=>{
            this.dict_coach = res
            this.coachData = res
          })
          pcm4sport().then(res=>{
            this.dict_sport = res
          })
          meta_scenario().then(res=>{
            res.data.forEach(item=>{
              this.dict_scenario[item.scenarioId] = item.name
            })
          })
          getReportClass({purposeId:this.usageId}).then(res=>{
            res.data.forEach(item=>{
              this.dict_reportClass[item.reportClassId] = item.name
            })
          })
          currentRolePlayer().then(res=>{
            this.dict_player = res
            this.playerData = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultDataList.length
          this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
.container{
  padding: 10px;
  background-color: #FFFFFF;
}
</style>
